package com.adt.studioms.api;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.adt.studioms.om.Service;
import com.asao.baseware.core.api.hibernate.HibernateDAOAwareAPI;

public class ServiceAPI extends HibernateDAOAwareAPI<Service> {

    protected Class<Service> getEntityClass() {
        return Service.class;
    }

    public Service get(long taskId, long photoSizeId) {
        DetachedCriteria criteria = DetachedCriteria.forClass(getEntityClass());
        criteria.add(Restrictions.eq("task.id", taskId));
        if (photoSizeId>0)
            criteria.add(Restrictions.eq("photoSize.id", photoSizeId));
        
        List<Service> services = dao.findByCriteria(criteria, 0, 1);
        return services.size()>0 ? services.get(0) : null;
    }
    
    public Service createService(long taskId, long photoSizeId, long price) {
        TaskAPI taskAPI = otherAPI(TaskAPI.class);
        PhotoSizeAPI psAPI = otherAPI(PhotoSizeAPI.class);
        
        Service s = new Service();
        s.setTask(taskAPI.get(taskId));
        s.setPhotoSize(psAPI.get(photoSizeId));
        s.setPrice(price);
        s.createSnapshot();
        dao.save(s);
        return s;
    }

    public Service updateService(long serviceId, long newTaskId, long newPhotoSizeId, long newPrice) {
        Service s = get(serviceId);
        if (s!=null) {
            TaskAPI taskAPI = otherAPI(TaskAPI.class);
            PhotoSizeAPI psAPI = otherAPI(PhotoSizeAPI.class);

            s.setTask(taskAPI.get(newTaskId));
            s.setPhotoSize(psAPI.get(newPhotoSizeId));
            boolean priceChanged = s.getPrice()!=newPrice;
            if (priceChanged) {
                s.setPrice(newPrice);
                s.createSnapshot();
            }
            dao.update(s);
        }
        return s;
    }
    
    public void update(Service entity) {
        throw new RuntimeException("Do not support this method. Use updateService() instead");
    }
}
